package com.atguigu.tingshu.user.api;

import com.atguigu.tingshu.common.login.annotation.TingShuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    //Request URL: http://localhost:8500/api/user/wxLogin/wxLogin/0b3mVb1w3FQ7W33loX2w3vKGp64mVb1V

    @Operation(summary = "微信小程序登录")
    @GetMapping("/wxLogin/{code}")
    public Result wxLogin(@PathVariable(value = "code") String code ){
         Map<String,Object>  map=userInfoService.wxLogin(code);
        return Result.ok(map);
    }

    @Operation(summary = "微信小程序刷新")
    @GetMapping
    public Result refreshToken(){
        Map<String,Object>  map=null;
        try {
            map=userInfoService.refreshToken();
        } catch (Exception e) {
            return Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        }
        return Result.ok(map);
    }

    //Request URL: http://localhost:8500/api/user/wxLogin/getUserInfo
    @Operation(summary = "获取登录后的用户信息")
    @TingShuLogin
    @GetMapping("/getUserInfo")     //授权接口(用户id和openId是否携带,没有登录就不能获取用户信息)
    public Result getUserInfoVo(){
        Long userId = AuthContextHolder.getUserId();
        UserInfoVo userInfoVo= userInfoService.getUserInfoVo(userId);
        return Result.ok(userInfoVo);
    }


    //Request URL: http://localhost:8500/api/user/wxLogin/updateUser
    @Operation(summary = "更新用户信息")
    @TingShuLogin
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo){

        userInfoService.updateUser(userInfoVo);
        return Result.ok(null);
    }


}
